<template>
    <fieldset>
        <legend>失效函数的应用</legend>
        <h4 id="content">{{ content }}</h4>
        <button v-for="(btn, index) in buttons" :key="index" :class="{ active: index + 1 === page }"
            @click="pageChange(index + 1)">第{{ index + 1 }}页</button>
    </fieldset>
</template>

<script setup>
import { ref, onMounted, reactive, watchEffect } from 'vue'//watch,
import CancelPromise from './cancelPromise'

//声明三个按钮
let buttons = reactive(['第1页', '第2页', '第3页'])

//模拟三个请求

let api1 = signal => new CancelPromise((resolve, reject) => {
    setTimeout(() => {
        resolve("第一页的数据")
    }, 1000)
},signal)
let api2 = signal => new CancelPromise((resolve, reject) => {
    setTimeout(() => {
        resolve("第二页的数据")
    }, 1500)
},signal)
let api3 = signal => new CancelPromise((resolve, reject) => {
    setTimeout(() => {
        resolve("第三页的数据")
    }, 2000)
},signal)

let api = {
    api1,//1000
    api2,//2000
    api3 //3000
}

//声明一个响应式的变量
let content = ref('')

//声明一个第三方变量作为按钮的激活条件
let page = ref(1)
//点击分页，获取模拟请求的分页数据
let pageChange = (pageSize) => {
    //给三方作为激活条件的变量赋值
    page.value = pageSize
}

//封装一个获取内容的方法
/**
 * 
 * @param {Number} pageSize 传递给后台的页码
 * @param {Object} signal 控制器(AbortController)的signal对象
 */
let fetchData = (pageSize = 1,signal) => {
    api['api' + pageSize](signal)
        .then(res => {
            content.value = res;
        })
}

//使用watchEffect
// watch(page, (newValue,oldValue) => {
//     console.log(newValue);
//     fetchData(newValue)
// })
watchEffect(invalidate => {
    //声明一个控制
    let abortController = new AbortController();
    //获取signal对象
    let signal = abortController.signal;
    //发起请求，并且传入signal对象
    fetchData(page.value,signal)
    invalidate(() => {
        //页面切换之前，取消上一个promise
        abortController.abort()
    })
})

//页面加载的时候获取第一页的数据(不空白)
// onMounted(() => {
//     fetchData()
// })

</script>


<style>
.active {
    background-color: skyblue;
}
</style>